import BlackjackGame as Game


# This function takes a file name and reads the contents of that file into
# the player_name and player_scores lists passed as a parameter into the
# function.
#
# The function returns the number of players read in from the file.
# You should make sure that you do not exceed the size of the lists (i.e. size
# of 5).  The player_names and player_scores lists should not exceed 5 elements.
def read_file(filename, player_names, player_scores):
    file_origin = open(filename)
    i = 0
    for line in file_origin:
        #split the line string into 3 parts
        info = line.split(' ')
        player_names[i] = info[0]+' '+info[1]
        # remove the \n behind the scores
        player_scores[i] = int(info[2].split('\n')[0])
        i += 1

# This function will output the contents of the player_names and player_scores
# lists to a file in the same format as the input file.
#
# The file will need to be opened for writing in this function (and of course
# closed once all writing has been done).
#
# The function accepts the filename of the file to write to, the player_names
# and player_scores lists.
def write_to_file(filename, player_names, player_scores):
    file_output = open(filename, 'w')
    for i in range(0, len(player_names)):
        if player_names[i] != '':
            line = str(player_names[i]) + ' ' + str(player_scores[i]) + '\n'
            file_output.write(line)
    file_output.close()

# This function will take the player_names list and the player_scores list
# as parameters and will output the contents of the lists to the screen.
#
# This function displays the information to the screen in the format
# specified in the assignment specifications under the section - 'Screen Format'.
def display_high_scores(player_names, player_scores):
    # '*****************************************************'
    print('*' * 53)
    # '******************    Blackjack    ******************'
    print('*' * 18 + format('Blackjack', '^17s') + '*' * 18)
    # '******************   HIGH SCORES   ******************'
    print('*' * 18 + format('HIGH SCORES', '^17s') + '*' * 18)
    #'*****************************************************'
    print('*' * 53)
    # '*      Player Name                   Score          *'
    # layout in the middle,alignment on the left
    print('*' + ' ' * 6 + format('Player Name', '<30s') + format('Score', '<8s') + ' ' * 7 + '*')
    # '*****************************************************'
    print('*' * 53) 
    # output lists of player's name and high_score
    for i in range(0, len(player_names)):
        if player_names[i] == '':
    # '*---------------------------------------------------*'
    # '*      ????????                      0              *'
            print('*' + '-' * 51 + '*')
            print('*' + ' ' * 6 + format('????????', '<30s') + format('0', '<8s') + ' ' * 7 + '*')
        else:
    # '*---------------------------------------------------*'
    # '*      Player Name                   10             *'
            print('*' + '-' * 51 + '*')
            print('*' + ' ' * 6 + format(player_names[i], '<30s') + format(str(player_scores[i]), '<8s') + ' ' * 7 + '*')
    # '*---------------------------------------------------*'
    # '*****************************************************'
    print('*' + '-' * 51 + '*')
    print('*' * 53)


# This function will take the player's name as input along with the player_names
# list and will return the 
# position (index) of the player found in the player_names list.  You must not
# use list methods in your solution.
#
# If more than one player exists with the same name, return the position
# of the player who has the highest score (i.e. first match found).
#
# If the player is not found, the function returns -1.
def find_player(player_names, name):
    for i in range(0, len(player_names)):
        if player_names[i] != '' and name == player_names[i]:
            return i
    return -1


# This function takes a player's score, and the player_scores list
# as input and determines whether the player is to be added to the
# high scores lists (player_names and player_scores).
#	
# If the player is to be added, the insertion position is returned from this function.
#
# If the player does not qualify to have their name recorded in the high scores lists,
# the function returns -1.  
def is_high_score(player_scores, new_score):
    for i in range(0, len(player_scores)):
        if new_score >= player_scores[i]:
            return i      
    return -1


# This function takes the high scores lists (player_names and player_scores),
# the player's name and score and the position to insert the player into the lists.
#
# The player is added to the high scores lists at the insert position.
# The high scores lists (player_names and player_scores) must be maintained in
# descending order of total score.  Where two players have the same total score, 
# the new player being added should appear first.
#
# (Hint: when inserting a player, simply shift all elements one position down the lists.
# You must make sure you are not exceeding list bounds and that your lists do not contain
# more than five elements).  You must not use list methods in your solution.
#
# The function returns the number of high scores stored in the lists.    
def add_player(player_names, player_scores, new_name, new_score, insert_position):    
    if insert_position != len(player_names) - 1:
        for i in range(len(player_names) - 1, insert_position, -1):
            player_names[i] = player_names[i - 1]
            player_scores[i] = player_scores[i - 1]
    player_names[insert_position] = new_name
    player_scores[insert_position] = new_score

# Define lists to store high scores - player_names and player_scores lists
player_names = ["", "", "", "", ""]
player_scores = [0, 0, 0, 0, 0]

def scores_command():
    display_high_scores(player_names, player_scores)

def search_command():
    name = input('Please input name to be found:')
    index = find_player(player_names, name)
    if index == -1:
        print(name,'does not have a high scores entry.')
    else:
        print(name,'has a high score of ', player_scores[index])

def play_command():
    new_score = Game.play_blackjack()
    pos = is_high_score(player_scores,new_score)
    if pos != -1:
        # Insert the new_name and new_score to the player lists.
        print('Congratulations! You have made it into the BlackJack Hall of Fame!')
        new_name = input('Please input your name:')
        add_player(player_names, player_scores, new_name, new_score, pos)
        print('Successfully added ', new_name, ' to BlackJack Hall of Fame.')
    else:
        # New_score is not high score
        print('Sorry - you did not make it into the BlackJack Hall of Fame!')


# TEST SECTION
# START WITH INTERACTIVE MENU

menu_func = input('Please enter command [scores, search, play, quit]:')

while menu_func not in ['scores', 'search', 'play', 'quit']:
    print('Not a valid command - please try again.')
    menu_func = input('\nPlease enter command [scores, search, play, quit]:')

if menu_func != 'quit':
    read_file('high_scores.txt', player_names, player_scores) 
    while menu_func != 'quit':
        if menu_func == 'scores':
            scores_command()
        elif menu_func == 'search':
            search_command()
        elif menu_func == 'play':
            play_command()
        else:
            print('Not a valid command - please try again.')
        menu_func = input('\nPlease enter command [scores, search, play, quit]:')
    print('Goodbye - thanks for playing!\n')
    # Write scores to file and end the program.
    write_to_file('new_scores.txt', player_names, player_scores)
